package argo.hot100.linklist;

public class ReverseKGroup {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(1);
        dummy.next = head;
        ListNode preNode = dummy, cur = head;
        while (cur != null) {
            ListNode chk = cur;
            int count = 0;
            while (count < k && chk != null) {
                count++;
                chk = chk.next;
            }
            if (count < k) break;


            ListNode groupHead = null;
            ListNode groupTail = cur;
            for (int i = 0; i < k; i++) {
                ListNode nxt = cur.next;
                cur.next = groupHead;
                groupHead = cur;
                cur = nxt;
            }
            preNode.next = groupHead;
            groupTail.next = cur;
            preNode = groupTail;
        }
        return dummy.next;

    }


}
